/**
 * 应收账款模块JS
 */
$(function() {
    // 初始化表格
    var table = $('#table');

    // 初始化表格参数配置
    table.bootstrapTable({
        url: '/admin/erp/accounts_receivable/index',
        columns: [
            {
                field: 'id',
                title: 'ID',
                align: 'center',
                width: 50
            },
            {
                field: 'order_no',
                title: '订单编号',
                align: 'center',
                formatter: function(value, row) {
                    return row.salesOrder ? row.salesOrder.order_no : '';
                }
            },
            {
                field: 'customer_name',
                title: '客户名称',
                align: 'center',
                formatter: function(value, row) {
                    return row.customer ? row.customer.name : '';
                }
            },
            {
                field: 'amount',
                title: '金额',
                align: 'right',
                formatter: function(value) {
                    return value.toFixed(2);
                }
            },
            {
                field: 'due_date',
                title: '到期日期',
                align: 'center'
            },
            {
                field: 'status_text',
                title: '状态',
                align: 'center'
            },
            {
                field: 'create_time',
                title: '创建时间',
                align: 'center'
            },
            {
                field: 'operate',
                title: '操作',
                align: 'center',
                width: 250,
                events: operateEvents,
                formatter: operateFormatter
            }
        ],
        pagination: true,
        sidePagination: 'server',
        pageSize: 10,
        pageList: [10, 20, 50, 100],
        search: false,
        showColumns: true,
        showRefresh: true,
        minimumCountColumns: 2,
        queryParams: function(params) {
            return {
                limit: params.limit,
                offset: params.offset,
                order_no: $('#order_no').val(),
                customer_id: $('#customer_id').val(),
                status: $('#status').val(),
                start_date: $('#start_date').val(),
                end_date: $('#end_date').val()
            };
        }
    });

    // 操作列格式化
    function operateFormatter(value, row, index) {
        var html = '';
        html += '<a href="/admin/erp/accounts_receivable/detail/' + row.id + '" class="btn btn-xs btn-primary">详情</a> ';
        if (row.status == 0) {
            html += '<a href="/admin/erp/accounts_receivable/edit/' + row.id + '" class="btn btn-xs btn-success">编辑</a> ';
            html += '<button class="btn btn-xs btn-info confirm-btn" data-id="' + row.id + '">确认</button> ';
        }
        if (row.status == 1 || row.status == 3) {
            html += '<button class="btn btn-xs btn-warning receive-btn" data-id="' + row.id + '">标记收讫</button> ';
        }
        if (row.status == 0) {
            html += '<button class="btn btn-xs btn-danger delete-btn" data-id="' + row.id + '">删除</button> ';
        }
        return html;
    }

    // 操作列事件
    window.operateEvents = {
        'click .confirm-btn': function(e, value, row, index) {
            layer.confirm('确定要确认此应收账款吗？', function(index) {
                $.ajax({
                    url: '/admin/erp/accounts_receivable/confirm/' + row.id,
                    type: 'post',
                    dataType: 'json',
                    success: function(res) {
                        if (res.code == 1) {
                            layer.msg(res.msg, {icon: 1});
                            table.bootstrapTable('refresh');
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('网络错误', {icon: 2});
                    }
                });
                layer.close(index);
            });
        },
        'click .receive-btn': function(e, value, row, index) {
            layer.prompt({
                formType: 2,
                title: '请输入收款备注',
                area: ['400px', '200px']
            }, function(remark, index) {
                $.ajax({
                    url: '/admin/erp/accounts_receivable/receive/' + row.id,
                    type: 'post',
                    data: {remark: remark},
                    dataType: 'json',
                    success: function(res) {
                        if (res.code == 1) {
                            layer.msg(res.msg, {icon: 1});
                            table.bootstrapTable('refresh');
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('网络错误', {icon: 2});
                    }
                });
                layer.close(index);
            });
        },
        'click .delete-btn': function(e, value, row, index) {
            layer.confirm('确定要删除此应收账款吗？', function(index) {
                $.ajax({
                    url: '/admin/erp/accounts_receivable/del/' + row.id,
                    type: 'post',
                    dataType: 'json',
                    success: function(res) {
                        if (res.code == 1) {
                            layer.msg(res.msg, {icon: 1});
                            table.bootstrapTable('remove', {field: 'id', values: [row.id]});
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('网络错误', {icon: 2});
                    }
                });
                layer.close(index);
            });
        }
    };

    // 搜索按钮事件
    $('#search-btn').click(function() {
        table.bootstrapTable('refresh');
    });

    // 重置按钮事件
    $('#reset-btn').click(function() {
        $('#order_no').val('');
        $('#customer_id').val('');
        $('#status').val('');
        $('#start_date').val('');
        $('#end_date').val('');
        table.bootstrapTable('refresh');
    });

    // 添加应收账款按钮事件
    $('#add-btn').click(function() {
        window.location.href = '/admin/erp/accounts_receivable/add';
    });

    // 日期选择器初始化
    laydate.render({
        elem: '#start_date',
        type: 'date'
    });

    laydate.render({
        elem: '#end_date',
        type: 'date'
    });

    // 订单选择变化事件
    $('#order_id').change(function() {
        var orderId = $(this).val();
        if (orderId) {
            $.ajax({
                url: '/admin/erp/accounts_receivable/getOrderInfo',
                type: 'get',
                data: {order_id: orderId},
                dataType: 'json',
                success: function(res) {
                    if (res.code == 1) {
                        $('#customer_id').val(res.data.customer_id);
                        $('#amount').val(res.data.amount);
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                },
                error: function() {
                    layer.msg('网络错误', {icon: 2});
                }
            });
        } else {
            $('#customer_id').val('');
            $('#amount').val('');
        }
    });
});

/**
 * 添加/编辑表单提交
 */
function submitForm() {
    var form = $('#form');
    // 表单验证
    form.validate({
        rules: {
            order_id: {
                required: true
            },
            customer_id: {
                required: true
            },
            amount: {
                required: true,
                number: true,
                min: 0.01
            },
            due_date: {
                required: true
            }
        },
        messages: {
            order_id: {
                required: '请选择订单'
            },
            customer_id: {
                required: '请选择客户'
            },
            amount: {
                required: '请输入金额',
                number: '请输入有效的数字',
                min: '金额必须大于0'
            },
            due_date: {
                required: '请选择到期日期'
            }
        },
        submitHandler: function(form) {
            // 提交表单
            $.ajax({
                url: $(form).attr('action'),
                type: 'post',
                data: $(form).serialize(),
                dataType: 'json',
                success: function(res) {
                    if (res.code == 1) {
                        layer.msg(res.msg, {icon: 1});
                        setTimeout(function() {
                            window.location.href = '/admin/erp/accounts_receivable/index';
                        }, 1500);
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                },
                error: function() {
                    layer.msg('网络错误', {icon: 2});
                }
            });
        }
    });
}

// 页面加载完成后执行
$(document).ready(function() {
    // 如果是添加或编辑页面，初始化表单提交
    if ($('#form').length > 0) {
        submitForm();
    }
});